package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelVendor;
import com.micro.ai.models.mapper.ModelVendorMapper;
import com.micro.ai.models.service.ModelVendorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 模型供应商服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelVendorServiceImpl extends ServiceImpl<ModelVendorMapper, ModelVendor> implements ModelVendorService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelVendor create(ModelVendor vendor) {
        // 参数校验
        if (vendor == null) {
            throw new BusinessException("M0000", "供应商信息不能为空");
        }
        
        // 检查供应商代码是否已存在
        LambdaQueryWrapper<ModelVendor> query = new LambdaQueryWrapper<>();
        query.eq(ModelVendor::getTenantId, vendor.getTenantId())
             .eq(ModelVendor::getVendorCode, vendor.getVendorCode());
        
        ModelVendor existing = this.getOne(query);
        if (existing != null) {
            throw new BusinessException("M0001", "供应商代码已存在: " + vendor.getVendorCode());
        }
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        vendor.setCreatedAt(now);
        vendor.setUpdatedAt(now);
        
        // 保存到数据库
        boolean success = this.save(vendor);
        if (!success) {
            throw new BusinessException("M0003", "保存供应商失败");
        }
        
        log.info("创建模型供应商成功: vendorId={}, vendorCode={}, vendorName={}", 
                vendor.getId(), vendor.getVendorCode(), vendor.getVendorName());
        
        return vendor;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelVendor update(String id, ModelVendor vendor) {
        // 参数校验
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "供应商ID不能为空");
        }
        if (vendor == null) {
            throw new BusinessException("M0000", "供应商信息不能为空");
        }
        
        // 检查供应商是否存在
        ModelVendor existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("M0002", "供应商不存在: " + id);
        }
        
        // 检查供应商代码是否被其他供应商使用
        if (!existing.getVendorCode().equals(vendor.getVendorCode())) {
            LambdaQueryWrapper<ModelVendor> query = new LambdaQueryWrapper<>();
            query.eq(ModelVendor::getTenantId, vendor.getTenantId())
                 .eq(ModelVendor::getVendorCode, vendor.getVendorCode())
                 .ne(ModelVendor::getId, id);
            
            ModelVendor duplicate = this.getOne(query);
            if (duplicate != null) {
                throw new BusinessException("M0001", "供应商代码已被其他供应商使用: " + vendor.getVendorCode());
            }
        }
        
        // 设置ID和更新时间
        vendor.setId(id);
        vendor.setUpdatedAt(LocalDateTime.now());
        
        // 更新到数据库
        boolean success = this.updateById(vendor);
        if (!success) {
            throw new BusinessException("M0003", "更新供应商失败");
        }
        
        log.info("更新模型供应商成功: vendorId={}, vendorCode={}", id, vendor.getVendorCode());
        
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        // 参数校验
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "供应商ID不能为空");
        }
        
        // 检查供应商是否存在
        ModelVendor vendor = this.getById(id);
        if (vendor == null) {
            throw new BusinessException("M0002", "供应商不存在: " + id);
        }
        
        // 注意：由于外键约束，如果有关联的模型定义，数据库会自动阻止删除
        // 这里可以提供更友好的错误提示
        
        // 删除供应商
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("M0003", "删除供应商失败");
        }
        
        log.info("删除模型供应商成功: vendorId={}, vendorCode={}", id, vendor.getVendorCode());
    }

    @Override
    public Page<ModelVendor> pageQuery(int pageNum, int pageSize, String tenantId, String keyword, String status) {
        // 参数校验
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        // 构建查询条件
        Page<ModelVendor> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ModelVendor> query = new LambdaQueryWrapper<>();
        
        // 租户ID筛选
        if (StringUtils.hasText(tenantId)) {
            query.eq(ModelVendor::getTenantId, tenantId);
        }
        
        // 关键词模糊搜索
        if (StringUtils.hasText(keyword)) {
            query.and(q -> q.like(ModelVendor::getVendorName, keyword)
                          .or().like(ModelVendor::getVendorCode, keyword)
                          .or().like(ModelVendor::getDescription, keyword));
        }
        
        // 状态筛选
        if (StringUtils.hasText(status)) {
            query.eq(ModelVendor::getStatus, status);
        }
        
        // 按创建时间倒序排列
        query.orderByDesc(ModelVendor::getCreatedAt);
        
        // 执行分页查询
        return this.page(page, query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String id, String status) {
        // 参数校验
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("M0000", "供应商ID不能为空");
        }
        if (!StringUtils.hasText(status)) {
            throw new BusinessException("M0000", "状态不能为空");
        }
        
        // 校验状态值是否合法
        if (!"active".equals(status) && !"inactive".equals(status)) {
            throw new BusinessException("M0000", "状态值不正确，只能是active或inactive");
        }
        
        // 检查供应商是否存在
        ModelVendor vendor = this.getById(id);
        if (vendor == null) {
            throw new BusinessException("M0002", "供应商不存在: " + id);
        }
        
        // 保存旧状态用于日志记录
        String oldStatus = vendor.getStatus();
        
        // 更新状态
        vendor.setStatus(status);
        vendor.setUpdatedAt(LocalDateTime.now());
        
        // 保存到数据库
        boolean success = this.updateById(vendor);
        if (!success) {
            throw new BusinessException("M0003", "更新供应商状态失败");
        }
        
        log.info("更新供应商状态成功: vendorId={}, vendorCode={}, oldStatus={}, newStatus={}", 
                id, vendor.getVendorCode(), oldStatus, status);
    }
}
